package com.heeexy.example.service;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.dao.ArticleDao;
import com.heeexy.example.dao.UserDao;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.constants.ErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private UserDao userDao;
    /**
     * 新增文章
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject addArticle(JSONObject jsonObject) {
        Integer id = userDao.findIdByName(jsonObject.getString("owner"));
        JSONObject commodity = new JSONObject();
        JSONObject picture = new JSONObject();
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        commodity.put("name",jsonObject.getString("name"));
        commodity.put("price",jsonObject.getString("price"));
        commodity.put("introduction",jsonObject.getString("introduction"));
        commodity.put("abrasion",jsonObject.getString("abrasion"));
        commodity.put("owner_id",id);
        commodity.put("category_id",jsonObject.getJSONArray("select").get(0));
        commodity.put("create_time",jsonObject.getString("startTime"));
        commodity.put("update_time",formatter.format(date));
        picture.put("name",jsonObject.getString("picname"));
        picture.put("path",jsonObject.getString("path"));
        if(id!= null && !id.equals("")){
            articleDao.addArticle(commodity);
            picture.put("commodity_id",articleDao.searchArticle(commodity));
            articleDao.insertPicture(picture);
        }
        else{
            return CommonUtil.errorJson(ErrorEnum.E_400);
        }
        return CommonUtil.successJson();
    }

    /**
     * 文章列表
     */
    public JSONObject listArticle(JSONObject jsonObject) {
        CommonUtil.fillPageParam(jsonObject);
        int count = articleDao.countArticle(jsonObject);
        List<JSONObject> list = articleDao.listArticle(jsonObject);
        return CommonUtil.successPage(jsonObject, list, count);
    }

    /**
     * 更新文章
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateArticle(JSONObject jsonObject) {
        articleDao.updateArticle(jsonObject);
        return CommonUtil.successJson();
    }
}
